
"use strict";

angular.module('app.project').controller('MyTaskCtrl', function ($scope, projectHttpS, documentHttpS ,$http, $cookieStore,$stateParams) {
    //配置分页基本参数
    // $scope.paginationConf = {
    //     currentPage: 1,
    //     itemsPerPage: 10,
    //     pagesLength: 5,
    //     totalItems:20,
    //     perPageOptions: [10, 20, 30, 40, 50],
    //     plan:0,
    //     onChange: function(){
    //     }
    // };
    // $scope.$watch('paginationConf.currentPage + paginationConf.itemsPerPage', GetData);
    // console.log($stateParams.taskid);
    // 获取该任务的详细信息
    projectHttpS.gettaskinf($stateParams.taskid).then(function (response) {
        console.log(response);
        $scope.inf = response[0];
    });
    // 负责人的下拉菜单
    $scope.leaders = [];
    projectHttpS.getolduser($stateParams.projectid).then(function (response) {
    	console.log(response);
        if (response != undefined) {
            $scope.leaders = response;
        }
    });
    // 添加子任务
    // 显示子任务列表
    // 获取某个任务下的子任务列表
    var getchillist = function () {
        projectHttpS.gettaskchil_list($stateParams.taskid).then(function (response) {
            // 显示子任务

            if (response){
                show_task_list($stateParams.taskid, response);
            }
            
        });

    }
    getchillist();
    // 显示子任务列表
    var show_task_list = function (id, res) {

        $(".children_task_tbody").empty();
        for (var i = 0; i < res.length; i++) {
            var obj = res[i];
            var addTask = $('<tr> ' +
             '<td class="td_name" modifyid="' + obj.task_children_id + '">' +
               obj.task_children_name +
             '</td><td class="td_date" modifyid="' + obj.task_children_id + '">' +
                obj.end_date +
             '</td><td class="td_user" modifyid="' + obj.task_children_id + '">' +
                obj.manager_name +
             '</td><td class="text-align-right">' +
                // '<a href="javascript:void(0)" class="font-sm margin-right-5 modify_this">修改</a>'+
                '<a href="javascript:void(0)" class="font-sm del_this" delid="' + obj.task_children_id + '">删除</a></td>' +
             '</tr>');
            $(".children_task_tbody").append(addTask);
        }
        $("#task_number").text($(".children_task_tbody tr").length);
        // 删除子任务
        $(".del_this").each(function (i) {
            $(this).click(function (e) {
                //mydl.eq(i).hide("slow"); 
                var obj = {};
                obj.oper = "del";
                var arr = [];
                arr.push($(this).attr("delid"));
                obj.del_id = arr;
                projectHttpS.postAll1("taskChildrenOperation", obj).then(function (response) {
                    if (response > 0) {
                        getchillist();
                        $.smallBox({
                            title: "删除成功",
                            content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                            color: "#659265",
                            iconSmall: "fa fa-check fa-2x fadeInRight animated",
                            timeout: 4000
                        });
                    }
                });
            })

        });
        // 修改子任务的名称
        var update_name = function () {
            $(".td_name").click(function () {
                //mydl.eq(i).hide("slow"); 
                //名称框
                var txt_name = $(this).text();
                $(this).text("");
                var ipt_name = $('<input type="text" value="' + txt_name + '" class="form-control children_task_name">');
                $(this).append(ipt_name);
                $(this).unbind()
                // 名称框失去焦点时，修改数据库中该子任务的名称
                nameblur();
            })
        }
        update_name();
        var nameblur = function () {
            $(".children_task_name").blur(function () {
                if ($(this).val() != "") {
                    var mytxt = $(this).val();
                    // 将子任务添加到数据库
                    var obj = {};
                    obj.task_children_name = mytxt;
                    // obj.task_id = $stateParams.taskid;
                    obj.task_children_id = $(this).parent().attr("modifyid");
                    $(this).parent().text(mytxt);
                    $(this).remove();
                    projectHttpS.postAll1("update_taskChirdren_name", obj).then(function (response) {
                        if (response > 0) {
                            // 更新子任务列表
                            getchillist();
                            $.smallBox({
                                title: "添加成功",
                                content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                                color: "#659265",
                                iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                timeout: 4000
                            });
                        }
                    });
                }
                update_name();
            });
        }
        // 修改子任务截止时间
        var update_time = function () {
            $(".td_date").click(function () {
                var modify_date = $(this).text();
                $(this).text("");
                var ipt_date = $('<input type="date" value="' + modify_date + '" class="form-control children_task_date">');
                $(this).append(ipt_date);
                $(this).unbind();
                // 名称框失去焦点时，修改数据库中该子任务的名称
                dateblur();
            })
        }
        update_time();
        function dateblur() {
            $(".children_task_date").blur(function () {
                if ($(this).val() != "") {
                    var mytxt = $(this).val();
                    var obj = {};
                    obj.end_date = mytxt;
                    obj.task_children_id = $(this).parent().attr("modifyid");
                    $(this).parent().text(mytxt);
                    $(this).remove();
                    projectHttpS.postAll1("update_children_endDate", obj).then(function (response) {
                        if (response > 0) {
                            // 更新子任务列表
                            getchillist();
                            $.smallBox({
                                title: "添加成功",
                                content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                                color: "#659265",
                                iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                timeout: 4000
                            });
                        }
                    });
                }
                update_time();
            });
        }
        // 修改子任务的负责人
        var update_leader = function () {
            $(".td_user").click(function () {
                // 负责人框
                var modify_leader = $(this).text();
                $(this).text("");
                var ipt_user = $('<select class="form-control user_name"> <option value="">请选择</option></select>');
                $(this).append(ipt_user);
                // 负责人的下拉菜单
                for (var i = 0; i < $scope.leaders.length; i++) {
                    var id = $scope.leaders[i].user_id;
                    var name = $scope.leaders[i].name;
                    var option = $("<option value='" + id + "'>" + name + "</option>");
                    $(".user_name").append(option);
                }
                // 选中负责人
                $(".user_name").find("option[text='" + modify_leader + "']").attr("selected", true);
                $(this).unbind();
                // 名称框失去焦点时，修改数据库中该子任务的名称
                user_name_blur();
            })
        }
        update_leader();
        function user_name_blur() {
            $(".user_name").change(function () {
                var mytxt = $(this).find("option:selected").text();
                var obj = {};
                obj.task_children_id = $(this).parent().attr("modifyid");
                obj.manager_id = $(this).val();
                $(this).parent().text(mytxt);
                $(this).remove();
                console.log(obj);
                projectHttpS.postAll1("update_children_manager", obj).then(function (response) {
                    if (response > 0) {
                        // 更新子任务列表
                        getchillist();
                        $.smallBox({
                            title: "添加成功",
                            content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                            color: "#659265",
                            iconSmall: "fa fa-check fa-2x fadeInRight animated",
                            timeout: 4000
                        });
                    }
                });
                update_leader();

            })
        }
        // 修改
        // $(".modify_this").each(function(i){
        //     $(this).click(function(e){
        //         //mydl.eq(i).hide("slow"); 
        //         console.log(i);
        //    })
        // });
    }
    // 添加子任务
    $scope.add_children_task = function () {
        var pepo_name = $(".user_name").text();
        var ma_children_task = $('<tr> ' +
            '<td class="td_name">' +
              '<input type="text" placeholder="请输入任务名称" class="form-control children_task_name"></td> ' +
            '<td class="td_date">' +
              '<input type="date"  class="form-control children_task_date"></td> ' +
            '<td class="td_user">' +
               '<select class="form-control user_name"> <option  >请选择</option> </select></td>' +
            '<td class="text-align-right">' +
               '<a href="javascript:void(0)" class="font-sm margin-right-5  addtask">保存</a>' +
               '<a href="javascript:void(0)" class="font-sm margin-right-5 modify">修改</a>' +
               '<a href="javascript:void(0)" class="font-sm remove_this">删除</a></td>' +
            '</tr>');
        $(".children_task_tbody").prepend(ma_children_task);
        // 负责人的下拉菜单
        for (var i = 0; i < $scope.leaders.length; i++) {
            var id = $scope.leaders[i].user_id;
            var name = $scope.leaders[i].name;
            var option = $("<option value='" + id + "'>" + name + "</option>");
            $(".user_name").append(option);
        }

        // $("#task_number").text($(".children_task_tbody tr").length);
        // 名称框失去焦点
       // nameblur();
        function nameblur() {
            $(".children_task_name").blur(function () {
                if ($(this).val() != "") {
                    var mytxt = $(this).val();
                    $(this).parent().text(mytxt);
                    $(this).remove();
                    // 将子任务添加到数据库
                    var obj = {};
                    var obj2 = {};
                    obj.oper = "add";
                    obj2.task_children_name = mytxt;
                    obj2.task_id = $stateParams.taskid;
                    // obj2.manager_id = $(".childrenuser").val();
                    obj.insert = obj2;
                    console.log(obj);
                    projectHttpS.postAll1("taskChildrenOperation", obj).then(function (response) {
                        if (response > 0) {
                            // 更新子任务列表
                            getchillist();
                            $(this).parents('tr').remove();
                            $.smallBox({
                                title: "添加成功",
                                content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                                color: "#659265",
                                iconSmall: "fa fa-check fa-2x fadeInRight animated",
                                timeout: 4000
                            });
                        }
                    });
                }
            });
        }

        // 日期框失去焦点
        // dateblur();
        function dateblur() {
            $(".children_task_date").blur(function () {
                if ($(this).val() != "") {
                    var mytxt = $(this).val();
                    $(this).parent().text(mytxt);
                    $(this).remove();
                }
            });
        }

        // 负责人失去焦点
        // user_name_blur();
        function user_name_blur() {
            $(".user_name").change(function () {
                var mytxt = $(this).find("option:selected").text();
                $(this).parent().text(mytxt);
                $(this).remove();
            })
        }

        //添加子任务
        $(".addtask").click(function () {
        
            var obj = {};
            var obj2 = {};
            obj.oper = "add";
            obj2.task_children_name = $(".children_task_name").val();
            obj2.task_id = $stateParams.taskid;
            obj2.manager_id =  $(".user_name").val();
            obj2.end_date = $(".children_task_date").val();
            // obj2.manager_id = $(".childrenuser").val();
            obj.insert = obj2;
            projectHttpS.postAll1("taskChildrenOperation", obj).then(function (response) {
                if (response && response > 0) {
                    // 更新子任务列表
                   getchillist();
                    $(this).parents('tr').remove();
                    $.smallBox({
                        title: "添加成功",
                        content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                        color: "#659265",
                        iconSmall: "fa fa-check fa-2x fadeInRight animated",
                        timeout: 4000
                    });
                }
            });
        
        })

     

        // 修改
        $(".modify").click(function () {
            // 名称框
            var txt_name = $(this).parent().siblings('.td_name').text();
            $(this).parent().siblings('.td_name').text("");
            var ipt_name = $('<input type="text" value="' + txt_name + '" class="form-control children_task_name">');
            $(this).parent().siblings('.td_name').append(ipt_name);
            // 日期框
            var modify_date = $(this).parent().siblings('.td_date').text();
            // console.log(modify_date);
            $(this).parent().siblings('.td_date').text("");
            var ipt_date = $('<input type="date" value="' + modify_date + '" class="form-control children_task_date">');
            $(this).parent().siblings('.td_date').append(ipt_date);
            // 负责人框
            var modify_leader = $(this).parent().siblings('.td_user').text();
            $(this).parent().siblings('.td_user').text("");
            var ipt_user = $('<select class="form-control user_name"> <option value="">请选择</option></select>');
            $(this).parent().siblings('.td_user').append(ipt_user);
            // 负责人的下拉菜单
        	console.log($scope.leaders);
            for (var i = 0; i < $scope.leaders.length; i++) {
                var id = $scope.leaders[i].user_id;
                var name = $scope.leaders[i].name;
                var option = $("<option value='" + id + "'>" + name + "</option>");
                $(".user_name").append(option);
            }
            // 选中负责人
            console.log(modify_leader);
            $(".user_name").find("option[text='" + modify_leader + "']").attr("selected", true);
            nameblur();
            dateblur();
            user_name_blur();
        });

        //删除
        $(".remove_this").click(function () {
            $(this).parents('tr').remove();
            // $("#task_number").text($(".children_task_tbody tr").length);
        })
    }

    // 文档上传
    // $scope.add_children_file = function () {
    //     $(".parents_row").remove();
    //     $('.file_left_pnd').show();
    //     $(".Up_load").show();
    //     $(".cancel_load").show();
    //     $('.sure').hide();
    //     $(".progress-bar").css({ "width": "0%" });
    //     $(".progress_text").text("0%");
    //     $(".progress_bar_box").hide();
    //     // $(".top_txt").text("选择要上传的文档");
    //     $("#file").modal("show");
    // }
    var fileArr = [];
    $scope.upload_change = function (files) {
        var fileObj = files[0];
        if (fileObj.name) {
            var flag = no_repeat(fileObj.name);
        } else {
            return;
        }

        if (flag == true) {
            return;
        }
        fileArr.push(fileObj);
        // 获取名字
        var MyName = fileObj.name;
        // 获取大小转换成M单位
        var MySize = fileObj.size / 1024;
        //console.log(MySize);

        if (MySize >= 1024) {
            MySize = parseFloat(fileObj.size / 1024 / 1024).toFixed(2) + "M";
        } else {
            MySize = parseFloat(fileObj.size / 1024).toFixed(2) + "KB";
        }

        var file_name = $("<div class='row parents_row'>" +
            "<div class='col-sm-8'><span>" + MyName + "</span><p class='msg msg" + MyName + "'  filename1='" + MyName + "'></p></div>" +
            "<div class='col-sm-2'><span class='Size'>" + MySize + "</span></div>" +
            "<div class='col-sm-2 pull-right'>" +
            "<i class='glyphicon glyphicon-trash delete_file' filename='" + MyName + "'></i>" +
            "<i class='glyphicon glyphicon-ok glyphicon_green success_load success_load" + MyName + "'></i>" +
            "</div>" +
            "</div>");

        // $(".failed_load").hide();
        $("#file_box").append(file_name);
        $(".msg").hide();
        var parents_row_length = $('.parents_row').length;
        // $('.top_txt').text(parents_row_length + "个文件被选中");
        // 删除行
        $(".delete_file").each(function () {
            $(this).click(function () {
                $(this).parents(".parents_row").remove();
                delete_filename($(this).attr("filename"));
                if ($('.parents_row').length == 0) {
                    // $('.top_txt').text("选择要上传的文档");
                } else {
                    var parents_row_length = $('.parents_row').length;
                    // $('.top_txt').text(parents_row_length + "个文件被选中");
                }
            });
        });
    }

    // 添加不重复的元素
    function no_repeat(filename) {
        for (var i = 0; i < fileArr.length; i++) {
            if (fileArr[i].name == filename) {
                return true;
            }
        }
        return false;


    }
    // 删除指定文件名
    function delete_filename(filename) {
        for (var i = 0; i < fileArr.length; i++) {
            var obj = fileArr[i].name;
            if (obj == filename) {
                fileArr.splice(i, 1);
                break;
            }
        }
        console.log(fileArr);
    }
    //点击上传progress-bar
    var progress_i = 0;
    $scope.up_load = function () {
        if ($('.parents_row').length != 0) {
            $(".progress_bar_box").show();
            more_file(progress_i);
            // $('.footer_bottom').hide();
            $(".Up_load").hide();
            $(".cancel_load").hide();
            $('.file_left_pnd').hide();
            $('.sure').show();
            $(".delete_file").hide();
            $('.success_load').show();
            var parents_row_length = $('.parents_row').length;
            // $('.top_txt').text(parents_row_length + "个文件已上传");
        };
    }
    // 多个文件上传
    function more_file(progress_i) {
        if (progress_i < fileArr.length) {
            move_upload(fileArr[progress_i]);
        }
    }
    var pid; 
    var taskid;
    function move_upload(fileObj) {
        var formData = new FormData();
        pid = $('#proid').val();
        taskid = $('#taskid').val();
        formData.append("file", fileObj);
        formData.append("project_id", pid);
        formData.append("task_id", taskid);
        $.ajax({
            url: appConfig.base[1].baseURI + "ProjectManager/upload",
            type: 'POST',
            // dataType: 'json',
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            beforeSend: function (xhr) {
            	  xhr.setRequestHeader("token", custom.token);
                  return xhr;
                // console.log("正在进行，请稍候");
            },
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                console.log(xhr);
                if (onprogress && xhr.upload) {
                    xhr.upload.addEventListener("progress", onprogress, false);
                    return xhr;
                }
            },
            success: function (response) {
                //  var res = JSON.parse(response);
                var res = response;
                console.log(res);
                if (res.ok !== null) {
                    console.log("成功");
                    getfiles();
                    console.log(res);
                    progress_i += 1;
                    more_file(progress_i);
                } else {
                    console.log("失败");
                    var name1 = fileObj.name;
                    var arr = $(".msg");
                    for (var i = 0; i < arr.length; i++) {
                        if ($(arr[i]).attr("filename1") == name1) {
                            $(arr[i]).show();
                            $(arr[i]).text(res.msg);
                            break;
                        }
                    }
                    // 上传下一个文件
                    progress_i += 1;
                    more_file(progress_i);
                }
            },
            error: function (response) {
                console.log("error");
            }
        });
        //方法为上传的进度条
        function onprogress(evt) {
            console.log(evt);
            var loaded = evt.loaded;     //已经上传大小情况
            var tot = evt.total;      //附件总大小
            var per = Math.floor(100 * loaded / tot);  //已经上传的百分比
            $(".progress-bar").css({
                "width": per + "%"
            });
            $(".progress_text").text(per + "%");
        }
    }
    // 显示文件列表
    var json1 = [{ "id": "1", "name": "min", "type": "doc", "size": "50kb" },
    { "id": "2", "name": "min", "type": "doc", "size": "50kb" },
    { "id": "3", "name": "min", "type": "doc", "size": "50kb" }];
    var getfiles = function () {
        projectHttpS.getfile_list($stateParams.taskid).then(function (response) {
            console.log(response);
            if (response) {
                $("#file_number").text(response.length);
                $scope.files = response;
            }else  {
                $("#file_number").text("0");
                $scope.files = [];
            }         
        });
    }
    getfiles();
    // 删除文档
    $scope.del_file = function (fileid) {
        console.log(fileid);
        projectHttpS.get_deldoc(fileid).then(function (response) {
            console.log(response);
            if (response > 0) {
                getfiles();
                $.smallBox({
                    title: "删除成功",
                    content: "<i class='fa fa-clock-o'></i> <i>编辑任务成功</i>",
                    color: "#659265",
                    iconSmall: "fa fa-check fa-2x fadeInRight animated",
                    timeout: 4000
                });
            }
        });
    }
    
    
    var server;
    // 单个图片上传
    $scope.uploadtoserver = function(){
    		documentHttpS.getAll("return_port").then(function(response){
    			server = response+"/postfiles/upload";
    		});
    }

    $scope.tasktoupload =function(){
    	console.log("111");
        $('#file_task').show();
        $("#file-task").fileinput({
            language: 'zh',
            uploadUrl: 'http://172.31.181.173:9061/postfiles/upload',// server,//$scope.server, // you must set a valid URL here else you will get an error
            allowedFileExtensions: ['jpg', 'png', 'gif','docx','doc','xlsx'],
            overwriteInitial: false,
            maxFileSize: 100000,
            maxFilesNum: 10,
            showPreview: true,
    //     uploadExtraData:{
    //        flag: 'abc'
    //     },
            ajaxSettings:{
                beforeSend:function(xhr){
                xhr.setRequestHeader('token',custom.token);
                }            
            }
        
        });
    }
    
    $scope.src ={};
    $("#file-task").on("fileuploaded", function (event, data, previewId, index) {
    	
        if(data.response!= null){
        	console.log("上传成功")
        	 $scope.src.serversrc= data.response.result;
        	$scope.src.file =data.files[0];
        	
        	$scope.src.filename =data.files[0].name;
        	$scope.src.filesize =data.files[0].size;
        	$scope.src.filetype =data.files[0].type;
        	$scope.src.taskid = $stateParams.taskid;
        	console.log($scope.src);
        	var head_pro_id = $cookieStore.get('project_id');
        	$scope.src.proid = head_pro_id;
        	projectHttpS.postAll1("uploadtoservertask",$scope.src).then(function (response) {
                 
        		 console.log(response);
                  
               })
        	
        }else{
        	console.log("上传失败")
        }
       
    });
   
  


});